package com.situ.mall.web.controller;

import com.situ.mall.common.exception.NoLoginException;
import com.situ.mall.common.service.ICartService;
import com.situ.mall.common.service.ILocationService;
import com.situ.mall.common.service.IProductService;
import com.situ.mall.common.util.RequestUtil;
import com.situ.mall.common.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * @author yangkx
 * @create 2023-09-19-13:37
 */
@Controller
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private ICartService cartService;
    @Autowired
    private IProductService productService;
    @Autowired
    private ILocationService locationService;

    //打开购物车
    @GetMapping("/page")
    public String page(Model model) {
        //登陆过，先从session中取出当前登录会员的ID
        Integer memberId = (int) RequestUtil.getSession().getAttribute("currentId");
        //再根据memberId去cart表中查该会员购物车中的所有商品，并取个名转发到页面
        model.addAttribute("products", cartService.selectAll(memberId));
        return "cart";
    }

    //添加到购物车
    @PostMapping("/save")
    @ResponseBody
    public ResultVO save(Integer pId) {
        Object o = RequestUtil.getCurrent();
        //如果没登陆，抛异常,401
        if (o == null) {
            throw new NoLoginException();
        }
        //登陆过，添加到购物车
        return cartService.saveProduct(pId);
    }

    //购物车内删除商品
    @PostMapping("/delete/{id}")
    @ResponseBody
    public void delete(@PathVariable("id")Integer productId) {
        //取出当前登陆会员的id
        Integer memberId = (int) RequestUtil.getSession().getAttribute("currentId");
        cartService.delete(productId,memberId);
    }


    //商品结算（接选中的商品的ids（字符串)，在mapper中遍历出来每一个cartId）
    @GetMapping("/order")
    public String order(Model model, String ids) {
        //登陆过，先从session中取出当前登录会员的ID
        Integer memberId = (int) RequestUtil.getSession().getAttribute("currentId");
        //购物车ids（根据用户id和商品ids，去购物车表里查购物车id，拼接ids）
        model.addAttribute("ids", cartService.selectByIds(ids, memberId));
        //商品信息
        model.addAttribute("products", productService.selectByIds(ids, memberId));
        //用户地址信息
        model.addAttribute("locations", locationService.selectByMemberId(memberId));
        return "order";
    }
}
